package top.dancun.gulimail.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.Query;

import top.dancun.gulimail.product.dao.CategoryDao;
import top.dancun.gulimail.product.entity.CategoryEntity;
import top.dancun.gulimail.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1.查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);



        //2.组装
        List<CategoryEntity> listtree = list.stream().filter((category) ->
                category.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(setChilren(menu, list));

            return menu;
        }).sorted((menu1, menu2) -> {
            if (menu1.getSort() == null || menu2.getSort() == null) {
                return 0;
            }
            return menu2.getSort() - menu1.getSort();

        }).collect(Collectors.toList());
//        2.1找出父类
        return listtree;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1.检查其他地方是否有引用是否
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> setChilren(CategoryEntity menu, List<CategoryEntity> list) {
        List<CategoryEntity> tree = list.stream().filter(category -> {

            return category.getParentCid().equals(menu.getCatId());
        }).map((category) -> {

            List<CategoryEntity> childrenNode = setChilren(category, list);
            category.setChildren(childrenNode);
            return category;
        }).sorted((menu1, menu2) -> {
            if (menu1.getSort() == null || menu2.getSort() == null) {
                return 0;
            }
            return menu1.getSort() - menu2.getSort();

        }).collect(Collectors.toList());

        return tree;
    }


}